package com.lideru.backstage.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lideru.backstage.entity.Advertising;
import com.lideru.backstage.handler.NoAuth;
import com.lideru.backstage.mapper.AdvertisingMapper;
import com.lideru.backstage.mapper.AdvertisingMapper;
import com.lideru.backstage.utils.common.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;


/**
 * @author lideru
 */
@RestController
@RequestMapping("/advertising")

public class AdvertisingController {
    @Resource
    AdvertisingMapper advertisingMapper;

    @PostMapping
    public Result<?> save(@RequestBody Advertising advertising ) {
      advertising.setGmtCreate(new Date());
      advertising.setGmtModified(new Date());
        int i = advertisingMapper.insert(advertising);
        if (i<1){
            return Result.error("-1","新增书本类型失败！");
        }
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody Advertising advertising) {
        advertising.setGmtModified(new Date());
        int i = advertisingMapper.updateById(advertising);
        if (i<1){
            return Result.error("-1","修改书本类型失败！");
        }
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id ) {
      Advertising advertising = advertisingMapper.selectOne(Wrappers.<Advertising>lambdaQuery()
                .eq(Advertising::getId, id));
        if (advertising != null) {
          advertisingMapper.deleteById(id);
            return Result.success();
        }
        return Result.error("403", "你没有权限");

    }

    @GetMapping("getAllAdvertising")
    @NoAuth
    public Result<?> getAllAdvertising(){
      return Result.success( advertisingMapper.selectList(Wrappers.<Advertising>lambdaQuery().eq(Advertising::getIsCarousel,1)))  ;
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search
                              ) {
        return Result.success(
              advertisingMapper.selectPage(new Page<>(pageNum, pageSize), Wrappers.<Advertising>lambdaQuery().like(Advertising::getName, search)));
    }
}
